package com.tiger.communal.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.tiger.common.utils.DateUtils;
import com.tiger.common.utils.StringUtils;
import com.tiger.communal.domain.ConstructionUnit;
import com.tiger.communal.domain.ConstructionUnitEnclosure;
import com.tiger.communal.mapper.ConstructionUnitEnclosureMapper;
import com.tiger.communal.service.ConstructionUnitOa;
import okhttp3.*;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author bai
 * Date on 2023/2/16  9:37
 * Description:
 */
@Service
public class ConstructionUnitOaImpl implements ConstructionUnitOa {

    @Autowired
    private ConstructionUnitEnclosureMapper unitEnclosureMapper;
    /**
     * 施工单位提交审批
     * @param constructionUnit 施工单位
     * @return
     */
    @Override
    public String oaConstructionUnit(ConstructionUnit constructionUnit) throws Exception {
        String url = "http://www.wxt.plus:22801/seeyon/rest/bpm/process/start?token="+constructionUnit.getToken();
        //获取合同发起参数，对应OA
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("appName", "collaboration");
        HashMap<String, Object> map1 = new HashMap<>();
        Map<String, Object> data1 = new HashMap<String, Object>();
        //OA默认数据源
        data1.put("templateCode", "SGDWSPD");
        data1.put("draft", "0");
        data1.put("attachments", new ArrayList<Long>());
        data1.put("relateDoc", "");
        data1.put("subject", "");
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        ConstructionUnitEnclosure enclosure = new ConstructionUnitEnclosure();
        enclosure.setUnitId(constructionUnit.getId());
        List<ConstructionUnitEnclosure> enclosureList = unitEnclosureMapper.selectConstructionUnitEnclosureList(enclosure);
        if (StringUtils.isNotEmpty(enclosureList)){
            long l = new Random().nextLong();
            for (int i = 0;enclosureList.size()-1>=i;i++){
                //合同文本
                Map<String, Object> map3 = new HashMap<>();
                map3.put("fileUrl",getOaFile(enclosureList.get(i).getUrl(),constructionUnit.getToken()));
                map3.put("sort",i+1);
                map3.put("subReference",l);
                list.add(map3);
            }
            map1.put("附件",l);
        }

        Map<String, Object> data2 = new HashMap<String, Object>();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        map1.put("单位名称",constructionUnit.getName());
        map1.put("提交日期", DateUtils.getDate());
        map1.put("单位类别",constructionUnit.getType());
        map1.put("法定代表人",constructionUnit.getLegalRepresentative());
        map1.put("单据ID",constructionUnit.getId());
        map1.put("地址",constructionUnit.getAddress());
        map1.put("联系人",constructionUnit.getContact());
        map1.put("联系人电话",constructionUnit.getContactPhone());
        map1.put("开户名",constructionUnit.getAccountName());
        map1.put("开户行",constructionUnit.getDepositBank());
        map1.put("银行账户",constructionUnit.getBankAccount());
        map1.put("统一社会信用代码",constructionUnit.getLicenseCode());
        map1.put("备注",constructionUnit.getRemark());
        map1.put("企业资质",constructionUnit.getQualification());

        //发起人
        Object id = getLoginId(constructionUnit.getToken(), constructionUnit.getLoginName());
        map1.put("发起人",id);//发起人
        data2.put("formmain_0035", map1);
        data2.put("thirdAttachments",list);
        data1.put("data", data2);

        map.put("data", data1);

        JSONObject object = new JSONObject(map);
        System.out.println(object);

        Response response = null;
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType,JSONObject.toJSONString(map));
        Request request = new Request.Builder().url(url).method("POST", body)
                .addHeader("User-Agent", "Apifox/1.0.0 (https://www.apifox.cn)").
                addHeader("Content-Type", "application/json").build();
        try {
            response = client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response.body().string();
    }

    @Override
    public Object getLoginId(String token,String loginName) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String result = "";
        Object id = "";
        try{
            // 创建客户端连接对象
            httpClient = HttpClients.createDefault();
            String url = "http://www.ntgrzc.com/seeyon/rest/orgMember"+"?token="+token+"&loginName="+loginName;
            HttpGet get = new HttpGet(url);

            // 获取返回对象
            response = httpClient.execute(get);

            // 整理返回值
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity,"utf-8");
            JSONObject object = JSONObject.parseObject(result);
            id = object.get("id");
        }catch (Exception  e){
            e.printStackTrace();
        }finally {
            try{
                httpClient.close();
                response.close();
            }catch (IOException i){
                i.printStackTrace();
            }

        }

        return id;
    }

    /**
     * 文件上传
     */
    private Object getOaFile(String address,String token) throws Exception {
        File file = getNetUrlHttp(address);
//        File file = getFile(address);
//        File file = null;
//        MultipartFile file1 = createMultipartFile(address);
        String url = "http://www.ntgrzc.com/seeyon/rest/attachment?token="+token;
//        file = multipartFileToFile(file);
        String path = file.getAbsolutePath();

        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MultipartBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("imagefile", FileToMultipartFile(file).getOriginalFilename(),
                        okhttp3.RequestBody.create(okhttp3.MediaType.parse("image/*"),
                                new File(path)))
                .addFormDataPart("serialnum", "1")
                .build();
        Request request = new Request.Builder()
                .url(url)
                .method("POST", (okhttp3.RequestBody) body)
                .addHeader("Content-Type", "multipart/form-data")
                .build();
        Response response = client.newCall(request).execute();

//        System.out.println(JSONObject.parseObject(response.body().string()));
        JSONObject jsonObject = JSONObject.parseObject(response.body().string());
        List<Map<String, Object>> list=(List<Map<String, Object>>)jsonObject.get("atts");
        return list.get(0).get("fileUrl");
    }




    public MultipartFile FileToMultipartFile(File oneFile) throws IOException
    {
        FileItem fileItem = new DiskFileItem("mainFile", Files.probeContentType(oneFile.toPath()), false, oneFile.getName(), (int) oneFile.length(), oneFile.getParentFile());
        InputStream input = null;
        OutputStream os = null;
        MultipartFile multipartFile = null;
        try {
            input = new FileInputStream(oneFile);
            os = fileItem.getOutputStream();
            IOUtils.copy(input, os);
            multipartFile = new CommonsMultipartFile(fileItem);
            input.close();
            os.close();
            return multipartFile;
        } catch (IOException ex) {
            throw new RuntimeException();
        } finally {
            if(input != null){
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(os != null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    private File getNetUrlHttp(String path) throws UnsupportedEncodingException {
        //对本地文件命名，path是http的完整路径，主要得到资源的名字

        String newUrl = tranformStyle(path);
        newUrl = newUrl.split("[?]")[0];
        String[] bb = newUrl.split("/");
        //得到最后一个分隔符后的名字
        String fileName = bb[bb.length - 1];
        //保存到本地的路径
        String filePath="d:\\audio\\"+fileName;
        File file = null;

        URL urlfile;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try{
            //判断文件的父级目录是否存在，不存在则创建
            file = new File(filePath);
            if(!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }
            try{
                //创建文件
                file.createNewFile();
            }catch (Exception e){
                e.printStackTrace();
            }
            //下载
            urlfile = new URL(newUrl);
            inputStream = urlfile.openStream();
            outputStream = new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead=inputStream.read(buffer,0,8192))!=-1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (null != outputStream) {
                    outputStream.close();
                }
                if (null != inputStream) {
                    inputStream.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    /**
     * 对中文字符进行UTF-8编码
     * @param source 要转义的字符串
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String tranformStyle(String source) throws UnsupportedEncodingException
    {
        char[] arr = source.toCharArray();
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < arr.length; i++)
        {
            char temp = arr[i];
            if(isChinese(temp))
            {
                sb.append(URLEncoder.encode("" + temp, "UTF-8"));
                continue;
            }
            sb.append(arr[i]);
        }
        return sb.toString();
    }

    /**
     * 判断是不是中文字符
     * @param c
     * @return
     */
    public static boolean isChinese(char c)
    {

        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);

        if(ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS

                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS

                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A

                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION

                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION

                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS)
        {

            return true;

        }

        return false;

    }
}
